package org.jeecg.modules.htxincailiao.account.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.*;
import org.jeecg.modules.htxincailiao.account.constant.HTAccountTypeEnum;
import org.jeecg.modules.htxincailiao.account.constant.HTSysRoleCodeEnum;
import org.jeecg.modules.htxincailiao.account.domain.bo.*;
import org.jeecg.modules.htxincailiao.account.domain.vo.HTUserInfoVO;
import org.jeecg.modules.htxincailiao.account.domain.vo.HTUserStatisticsVO;
import org.jeecg.modules.htxincailiao.account.entity.*;
import org.jeecg.modules.htxincailiao.account.mapper.HTAccountMapper;
import org.jeecg.modules.htxincailiao.account.mapper.HTMerchantMapper;
import org.jeecg.modules.htxincailiao.account.service.*;
import org.jeecg.modules.htxincailiao.address.entity.HTEnterpriseAddress;
import org.jeecg.modules.htxincailiao.address.service.IHTEnterpriseAddressService;
import org.jeecg.modules.htxincailiao.im.domain.bo.IMUserAddBO;
import org.jeecg.modules.htxincailiao.im.entity.IMUser;
import org.jeecg.modules.htxincailiao.im.service.impl.IMUserServiceImpl;
import org.jeecg.modules.htxincailiao.shop.entity.HTShop;
import org.jeecg.modules.htxincailiao.shop.service.IHTShopService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.mapper.SysUserDepartMapper;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.vendors.tencent.account.service.IHTTencentAccountService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;


//@Service
@Slf4j
@Service("HTAccountService")
public class HTAccountServiceImpl implements IHTAccountService {

    @Resource
    HTAccountMapper accountMapper;

    @Resource
    IHTMemberService memberService;

    @Resource
    IHTForumsExpertService forumsExpertService;

    @Resource
    IHTMerchantService merchantService;

    @Resource
    IHTEvaluationAgencyService evaluationAgencyService;

    @Resource
    IHTAllianceMemberService allianceMemberService;

    @Resource
    IHTAllianceService allianceService;

    @Resource
    IHTAllianceCouncilService allianceCouncilService;

    @Resource
    ISysUserService sysUserService;

    @Resource
    IHTShopService shopService;

    @Resource
    ISysRoleService sysRoleService;

    @Resource
    IMUserServiceImpl imUserService;

    @Resource
    IHTEnterpriseAddressService enterpriseAddressService;

    @Resource
    private SysUserDepartMapper sysUserDepartMapper;

    @Resource
    private SysDepartMapper sysDepartMapper;

    @Override
    public boolean editPhoneNumber(HTEditPhoneNumberBO bo, HTPlatformUser user) {
        String phoneNumber = bo.getPhoneNumber();

        if (oConvertUtils.isNotEmpty(user.getPhoneNumber()) && user.getPhoneNumber().equals(phoneNumber)) {
            throw new JeecgBootException("新手机号不能与原手机号相同");
        }
        HTUserUpdateBO updateBO = SmartBeanUtil.copy(user, HTUserUpdateBO.class);
        updateBO.setAccountType(HTAccountTypeEnum.values()[user.getAccountType()]);
        updateBO.setPhoneNumber(bo.getPhoneNumber());
        return updateUserInfo(updateBO);
    }

    @Override
    public boolean resetPassword(HTResetPasswordBO bo) {
        HTPlatformUser user = accountMapper.queryFrontendUserByPhoneNumber(bo.getPhoneNumber());

        // 修改密码
        if (bo.isEdit() && !user.getPassword().equals(bo.getOldPassword())) {
            if (!user.getPassword().equals(bo.getOldPassword())) {
                throw new JeecgBootException("原密码不正确");
            }
        }

        // 重置密码
        if (oConvertUtils.isNotEmpty(user.getPassword()) && user.getPassword().equals(bo.getPassword())) {
            throw new JeecgBootException("新密码不能与旧密码相同");
        }

        HTUserUpdateBO updateBO = SmartBeanUtil.copy(user, HTUserUpdateBO.class);
        updateBO.setAccountType(HTAccountTypeEnum.values()[user.getAccountType()]);
        updateBO.setPassword(bo.getPassword());
        updateBO.setSalt(bo.getSalt());

        return updateUserInfo(updateBO);
    }

    private void validateCertificateAuditParameters(HTCertificateSubmitBO bo) {
        HTPlatformUser user = queryFrontendUserByUsername(bo.getUsername());
        if (oConvertUtils.isEmpty(user)) {
            user = queryFrontendUserByPhoneNumber(bo.getPhoneNumber());
        }
        bo.setAccountType(HTAccountTypeEnum.values()[user.getAccountType()]);
        switch (bo.getAccountType()) {
            case FORUMS_EXPERT:
            case MERCHANT:
            case EVALUATION_AGENCY:
            case ALLIANCE:
            case ALLIANCE_MEMBER:
                if (oConvertUtils.isEmpty(bo.getCertificate())) {
                    throw new JeecgBootException("资质文件不能为空");
                }
                if (bo.getCertificate().equals(user.getCertificate())) {
                    throw new JeecgBootException("更新资质不能与原资质相同");
                }
                break;
            default:
                break;
        }

    }

    @Override
    public boolean certificateSubmit(HTCertificateSubmitBO bo) {
        validateCertificateAuditParameters(bo);
        HTPlatformUser user = queryFrontendUserByUsername(bo.getUsername());
        if (oConvertUtils.isEmpty(user)) {
            user = queryFrontendUserByPhoneNumber(bo.getPhoneNumber());
        }
        String phoneNumber = oConvertUtils.isNotEmpty(bo.getContactPhoneNumber())
                ? bo.getContactPhoneNumber() : user.getPhoneNumber();
        String contactPerson = oConvertUtils.isNotEmpty(bo.getContactPerson())
                ? bo.getContactPerson() : user.getUsername();

        HTUserUpdateBO updateBO = SmartBeanUtil.copy(user, HTUserUpdateBO.class);

        updateBO.setAccountType(HTAccountTypeEnum.values()[user.getAccountType()]);
        updateBO.setContactPerson(contactPerson);
        updateBO.setContactPhoneNumber(phoneNumber);

        if (oConvertUtils.isNotEmpty(bo.getBankAccountName())) {
            updateBO.setBankAccountName(bo.getBankAccountName());
        } else {
            throw new JeecgBootException("开户银行不能为空");
        }

        if (oConvertUtils.isNotEmpty(bo.getBankAccountNum())) {
            updateBO.setBankAccountNum(bo.getBankAccountNum());
        } else {
            throw new JeecgBootException("银行账号不能为空");
        }


        if (oConvertUtils.isNotEmpty(bo.getCertificate())) {
            updateBO.setCertificate(bo.getCertificate());
        } else {
            throw new JeecgBootException("资质文件不能为空");
        }

        if (oConvertUtils.isNotEmpty(bo.getOtherCertificates())) {
            updateBO.setOtherCertificates(bo.getOtherCertificates());
        }


        // 资质认证状态：0-未认证 1-认证中 2-已认证 3-认证驳回
        updateBO.setCertificateAuditStatus(1);


        return updateUserInfo(updateBO);
    }

    @Override
    public SysUser handleSysUserForSignUp(HTAccountAddBO bo) {
        //前端账户类型映射对应后端账户角色
        String roleCode = HTSysRoleCodeEnum.values()[bo.getAccountType().getValue()].getValue();

        //分配后台账户
        SysUser sysUser = SmartBeanUtil.copy(bo, SysUser.class);
        log.info("\n\nhandleSysUserForSignUp sysUser : {}\n\n", sysUser);
        SysUser signedUpSysUser = sysUserService.getUserByName(sysUser.getUsername());
        if (oConvertUtils.isEmpty(signedUpSysUser) && oConvertUtils.isNotEmpty(bo.getPhoneNumber())) {
            signedUpSysUser = sysUserService.getUserByPhoneNumber(bo.getPhoneNumber());
        }

        String salt = SaltUtil.salt();
        //后台管理账号默认随机密码
        String password = UUIDGenerator.generate();
        String mixedPassword = password + salt;
        String md5Password = Md5Util.md5Encode(mixedPassword, "");
        sysUser.setSalt(salt);
        sysUser.setPassword(md5Password);

        //已注册用户
        if (oConvertUtils.isNotEmpty(signedUpSysUser)) {
            if (oConvertUtils.isEmpty(signedUpSysUser.getPassword())) {
                signedUpSysUser.setSalt(salt);
                signedUpSysUser.setPassword(md5Password);
            }
            return signedUpSysUser;
        }

        //未注册用户 - 分配角色
        SysRole role = sysRoleService.queryByRoleCode(roleCode);
        try {
            SysDepart sysDepart = sysDepartMapper.getFirstDepart();
            String userId = sysUser.getId();
            String departId = sysDepart.getId();
            SysUserDepart userDepart = new SysUserDepart(userId, departId);
            sysUserDepartMapper.insert(userDepart);

            log.info("\n\nuserId : {}\n\n", userId);
            log.info("\n\nsysUserService : {}\n\n", sysUserService);
            // 这里用getUserById 不用getById是英文IAccountServe不支持 extends IService
            SysUser storedSysUser = sysUserService.getUserById(userId);
            log.info("\n\nstoredSysUser : {}\n\n", storedSysUser);
            if (oConvertUtils.isEmpty(storedSysUser)) {
                //为企业用户创建后台账户
                sysUserService.addUserWithRole(sysUser, role.getId());
            } else {
                storedSysUser.setSalt(salt);
                storedSysUser.setPassword(md5Password);
                sysUserService.updateById(storedSysUser);
                sysUser = storedSysUser;
            }

        } catch (Exception e) {
            throw new JeecgBootException("分配后台账户和角色失败！");
        }

        // 跟新IM用户，如果不存在就创建
        if (oConvertUtils.isNotEmpty(sysUser)) {
            IMUserAddBO imUserAddBO = SmartBeanUtil.copy(bo, IMUserAddBO.class);
            imUserAddBO.setUserId(sysUser.getId());
            boolean success = handleSignUpForImUser(imUserAddBO);
            if (!success) {
                throw new JeecgBootException("创建IM用户失败！");
            }
        }

        log.info("\n\nhandleSysUserForSignUp  返回 sysUser: {}\n\n", sysUser);

        return sysUser;
    }

    private HTShop handleShopForSignUp(HTAccountAddBO bo) {
        HTShop signedUpShop = shopService.queryByShopName(bo.getEnterpriseName());
        if (oConvertUtils.isNotEmpty(signedUpShop)) {
            return signedUpShop;
        } else {
            HTShop shop = new HTShop();
            shop.setName(bo.getEnterpriseName());
            shop.setIndustryCategoryId(bo.getIndustryCategoryId());
            shop.setLogo(bo.getLogo());
            shop.setSellerId(bo.getId());
            try {
                shopService.save(shop);
            } catch (Exception e) {
                throw new JeecgBootException("保存店铺失败！");
            }
            return shop;
        }
    }


    @Override
    public boolean certificateAudit(HTUserUpdateBO bo) {
        // 资质认证状态：0-未认证 1-认证中 2-已认证 3-认证驳回
        if (bo.getCertificateAuditStatus() == 2) {
            HTAccountAddBO accountAddBO = SmartBeanUtil.copy(bo, HTAccountAddBO.class);

            // 后台账号，角色验证
            SysUser sysUser = handleSysUserForSignUp(accountAddBO);
            if (oConvertUtils.isNotEmpty(sysUser)) {
                bo.setSysUserId(sysUser.getId());
            } else {
                throw new JeecgBootException("创建后台账户失败");
            }

            //前端账户类型映射对应后端账户角色
            String roleCode = HTSysRoleCodeEnum.values()[bo.getAccountType().getValue()].getValue();
            HTSysRoleCodeEnum roleCodeEnum = HTSysRoleCodeEnum.EnumValueOf(roleCode);
            switch (roleCodeEnum) {
                case ROLE_MERCHANT:
                case ROLE_EVALUATION_AGENCY:
                case ROLE_ALLIANCE:
                case ROLE_ALLIANCE_MEMBER:
                    // 店铺校验
                    HTShop shop = handleShopForSignUp(accountAddBO);
                    //更新sys_user表的shopId
                    if (oConvertUtils.isNotEmpty(shop)) {
                        sysUser.setShopId(shop.getId());
                        sysUserService.updateById(sysUser);
                    } else {
                        throw new JeecgBootException("创建店铺失败");
                    }
                    break;

                default:
                    break;
            }

        }


        return updateUserInfo(bo);
    }

    @Override
    public HTPlatformUser queryFrontendUserByUsername(String username) {
        return accountMapper.queryFrontendUserByUsername(username);
    }

    @Override
    public HTPlatformUser queryFrontendUserByEmail(String email) {
        return accountMapper.queryFrontendUserByEmail(email);
    }

    @Override
    public HTPlatformUser queryFrontendUserByPhoneNumber(String phoneNumber) {
        return accountMapper.queryFrontendUserByPhoneNumber(phoneNumber);
    }

    @Override
    public HTPlatformUser queryFrontendUserByMultipleFactor(String username, String phoneNumber, String email) {
        return accountMapper.queryFrontendUserByMultipleFactor(username, phoneNumber, email);
    }

    @Override
    public HTPlatformUser queryUserById(String id) {
        return accountMapper.queryUserById(id);
    }

    /*
     * 验证账号是否存在
     * username 用户名
     * phoneNumber 手机号
     * email 邮箱
     */
    @Override
    public boolean validateAccountExistByMultipleFactor(String username, String phoneNumber, String email) {
        HTPlatformUser platformUserByUsername = null;
        if (oConvertUtils.isNotEmpty(username)) {
            platformUserByUsername = accountMapper.queryFrontendUserByUsername(username);
        }
        HTPlatformUser platformUserByPhoneNumber = null;
        if (oConvertUtils.isNotEmpty(phoneNumber)) {
            try {
                platformUserByPhoneNumber = accountMapper.queryFrontendUserByPhoneNumber(phoneNumber);
            } catch (Exception e) {
                throw new JeecgBootException("查询用户失败！");
            }

        }
        HTPlatformUser platformUserByEmail = null;
        if (oConvertUtils.isNotEmpty(email)) {
            platformUserByEmail = accountMapper.queryFrontendUserByEmail(email);
        }
        return (platformUserByUsername != null) ||
                (platformUserByPhoneNumber != null) ||
                (platformUserByEmail != null);
    }

    private void validateEnterpriseUserParameters(HTAccountAddBO bo) {
        if (oConvertUtils.isEmpty(bo.getContactPerson())) {
            throw new JeecgBootException("联系人不能为空！");
        }
        if (oConvertUtils.isEmpty(bo.getPhoneNumber())) {
            throw new JeecgBootException("手机号不能为空！");
        }
    }

    public boolean handleSignUpForMerchant(HTAccountAddBO bo) {
        validateEnterpriseUserParameters(bo);

        boolean succeed = false;

        HTMerchant merchant = SmartBeanUtil.copy(bo, HTMerchant.class);
        if (oConvertUtils.isEmpty(bo.getAccountType())) {
            merchant.setAccountType(HTAccountTypeEnum.MERCHANT.getValue());
        }
//        merchant.setAccountType(HTAccountTypeEnum.MERCHANT.getValue());
        try {
            succeed = merchantService.save(merchant);
            if (succeed) {
                IMUserAddBO imUserAddBO = SmartBeanUtil.copy(bo, IMUserAddBO.class);
                succeed = handleSignUpForImUser(imUserAddBO);
            }

        } catch (Exception e) {
            throw new JeecgBootException("保存失败！");
        }

        try {
            HTEnterpriseAddress address = saveEnterpriseAddress(bo.getContactPerson(), bo.getPhoneNumber(), merchant.getEnterpriseName());

            merchant.setEnterpriseAddressId(address.getId());
            succeed = merchantService.updateById(merchant);
        } catch (Exception e) {
            throw new JeecgBootException("更新商户失败！");
        }

        return succeed;
    }

    public boolean handleSignUpForMember(HTAccountAddBO bo) {
        boolean succeed = false;
        HTMember member = SmartBeanUtil.copy(bo, HTMember.class);
        member.setAccountType(HTAccountTypeEnum.MEMBER.getValue());
        try {
            succeed = memberService.save(member);

            if (succeed) {
                IMUserAddBO imUserAddBO = SmartBeanUtil.copy(bo, IMUserAddBO.class);
                imUserAddBO.setUserId(member.getId());
                succeed = handleSignUpForImUser(imUserAddBO);
            }

        } catch (Exception e) {
            throw new JeecgBootException("保存平台会员失败！");
        }

        return succeed;
    }


    /*
     *
     */
    public boolean handleSignUpForImUser(IMUserAddBO bo) {
        boolean succeed = false;
        IMUser imUser = null;
        log.info("\n\nbo.getUserId() : {}\n\n", bo.getUserId());
        if (oConvertUtils.isEmpty( bo.getUserId())) {
            throw new JeecgBootException("创建IM用户中UserID不能为空");
        }
        IMUser storedImUser = imUserService.queryByUserId(bo.getUserId());

        if (oConvertUtils.isNotEmpty(storedImUser)) {
            if (oConvertUtils.isEmpty(bo.getUsername())) {
                storedImUser.setUsername(bo.getPhoneNumber());
            }
            BeanUtils.copyProperties(bo, storedImUser);

            try {
                succeed = imUserService.updateById(storedImUser);
            } catch (Exception e) {
                throw new JeecgBootException("更新IM用户失败！");
            }
        } else {
            imUser = SmartBeanUtil.copy(bo, IMUser.class);
            if (oConvertUtils.isEmpty(bo.getUsername())) {
                imUser.setUsername(bo.getPhoneNumber());
            }

            try {
                succeed = imUserService.save(imUser);
            } catch (Exception e) {
                throw new JeecgBootException("创建IM用户失败！");
            }
        }


        return succeed;
    }


    @Override
    public HTUserInfoVO getUserInfo(HTAccountTypeEnum accountType, String userId) {
        HTUserInfoVO userInfo = null;
        switch (accountType) {
            case MEMBER:
                HTMember member = memberService.getById(userId);
                userInfo = SmartBeanUtil.copy(member, HTUserInfoVO.class);
                break;

            case FORUMS_EXPERT:
                HTForumsExpert forumsExpert = forumsExpertService.getById(userId);
                userInfo = SmartBeanUtil.copy(forumsExpert, HTUserInfoVO.class);
                break;

            case MERCHANT:
                HTMerchant merchant = merchantService.getById(userId);
                userInfo = SmartBeanUtil.copy(merchant, HTUserInfoVO.class);
                if (oConvertUtils.isNotEmpty(merchant.getEnterpriseAddressId())) {
                    updateUserInfoWithAddressId(userInfo, merchant.getEnterpriseAddressId());
                }
                break;

            case EVALUATION_AGENCY:
                HTEvaluationAgency evaluationAgency = evaluationAgencyService.getById(userId);
                userInfo = SmartBeanUtil.copy(evaluationAgency, HTUserInfoVO.class);
                if (oConvertUtils.isNotEmpty(evaluationAgency.getEnterpriseAddressId())) {
                    updateUserInfoWithAddressId(userInfo, evaluationAgency.getEnterpriseAddressId());
                }

                break;

            case ALLIANCE:
                HTAlliance alliance = allianceService.getById(userId);
                userInfo = SmartBeanUtil.copy(alliance, HTUserInfoVO.class);
                if (oConvertUtils.isNotEmpty(alliance.getEnterpriseAddressId())) {
                    updateUserInfoWithAddressId(userInfo, alliance.getEnterpriseAddressId());
                }
                break;

            case ALLIANCE_COUNCIL:
                HTAllianceCouncil allianceCouncil = allianceCouncilService.getById(userId);
                userInfo = SmartBeanUtil.copy(allianceCouncil, HTUserInfoVO.class);

                break;

            case ALLIANCE_MEMBER:
                HTAllianceMember allianceMember = allianceMemberService.getById(userId);
                userInfo = SmartBeanUtil.copy(allianceMember, HTUserInfoVO.class);
                if (oConvertUtils.isNotEmpty(allianceMember.getEnterpriseAddressId())) {
                    updateUserInfoWithAddressId(userInfo, allianceMember.getEnterpriseAddressId());
                }
                break;

            default:
                break;
        }

        return userInfo;
    }

    private void updateUserInfoWithAddressId(HTUserInfoVO userInfo, String addressId) {
        if (oConvertUtils.isNotEmpty(addressId)) {
            HTEnterpriseAddress address =
                    enterpriseAddressService.getById(addressId);
            if (oConvertUtils.isNotEmpty(address)) {
                if (oConvertUtils.isNotEmpty(address.getContactPerson())) {
                    userInfo.setContactPerson(address.getContactPerson());
                }
                userInfo.setContactPhoneNumber(address.getPhoneNumber());
                userInfo.setEnterpriseAddressId(address.getId());
            }

        }
    }


    @Override
    @Transactional
    public boolean updateUserInfo(HTUserUpdateBO bo) {
        boolean succeed = false;
        try {
            switch (bo.getAccountType()) {
                case MEMBER:
                    HTMember member = SmartBeanUtil.copy(bo, HTMember.class);
                    succeed = memberService.updateById(member);
                    break;

                case FORUMS_EXPERT:
                    HTForumsExpert expert = SmartBeanUtil.copy(bo, HTForumsExpert.class);
                    succeed = forumsExpertService.updateById(expert);
                    break;

                case MERCHANT:
                    HTMerchant merchant = SmartBeanUtil.copy(bo, HTMerchant.class);
                    System.out.printf("\n\n\n merchant %s \n\n\n", JSONObject.toJSONString(bo));
                    String contactPhoneNumber = bo.getContactPhoneNumber();
                    if (oConvertUtils.isEmpty(contactPhoneNumber)) {
                        contactPhoneNumber = bo.getPhoneNumber();
                    }

                    String contactPerson = bo.getContactPerson();
                    if (oConvertUtils.isEmpty(contactPerson)) {
                        contactPerson = bo.getRealName();
                    }

                    if (oConvertUtils.isEmpty(contactPerson)) {
                        contactPerson = bo.getUsername();
                    }
                    if (oConvertUtils.isEmpty(contactPerson)) {
                        contactPerson = contactPhoneNumber;
                    }


                    updateEnterpriseAddress(contactPerson,
                            contactPhoneNumber,
                            merchant.getEnterpriseName(),
                            merchant.getEnterpriseAddressId());
                    succeed = merchantService.updateById(merchant);
                    break;

                case EVALUATION_AGENCY: {
                    HTEvaluationAgency evaluationAgency = SmartBeanUtil.copy(bo, HTEvaluationAgency.class);
                    updateEnterpriseAddress(bo.getContactPerson(),
                            bo.getContactPhoneNumber(),
                            bo.getId(),
                            evaluationAgency.getEnterpriseAddressId());
                    succeed = evaluationAgencyService.updateById(evaluationAgency);
                }
                break;

                case ALLIANCE:
                    HTAlliance alliance = SmartBeanUtil.copy(bo, HTAlliance.class);
                    updateEnterpriseAddress(bo.getContactPerson(),
                            bo.getContactPhoneNumber(),
                            bo.getId(),
                            alliance.getEnterpriseAddressId());
                    succeed = allianceService.updateById(alliance);
                    break;

                case ALLIANCE_COUNCIL:
                    HTAllianceCouncil allianceCouncil = SmartBeanUtil.copy(bo, HTAllianceCouncil.class);
                    succeed = allianceCouncilService.updateById(allianceCouncil);
                    break;

                case ALLIANCE_MEMBER:
                    HTAllianceMember allianceMember = SmartBeanUtil.copy(bo, HTAllianceMember.class);
                    updateEnterpriseAddress(bo.getContactPerson(),
                            bo.getContactPhoneNumber(),
                            bo.getId(),
                            allianceMember.getEnterpriseAddressId());
                    succeed = allianceMemberService.updateById(allianceMember);
                    break;

                default:
                    break;
            }
        } catch (Exception e) {
            System.out.printf("\n\n\n user update info exception %s \n\n\n", JSONObject.toJSONString(e));
            throw new JeecgBootException("操作失败");
        }

        return succeed;
    }

    private void updateEnterpriseAddress(String contactPerson,
                                         String phoneNumber,
                                         String enterpriseName,
                                         String addressId) {
        HTEnterpriseAddress address = enterpriseAddressService.getById(addressId);
        System.out.printf("\n\n\n %s \n\n\n", JSONObject.toJSONString(address));
        if (oConvertUtils.isNotEmpty(address)) {
            if (oConvertUtils.isNotEmpty(contactPerson)) {
                address.setContactPerson(contactPerson);
            }
            if (oConvertUtils.isNotEmpty(phoneNumber)) {
                address.setPhoneNumber(phoneNumber);
            }
            enterpriseAddressService.updateById(address);
        } else {
            saveEnterpriseAddress(contactPerson, phoneNumber, enterpriseName);
        }
    }

    private HTEnterpriseAddress saveEnterpriseAddress(String contactPerson, String phoneNumber, String enterpriseName) {
        HTEnterpriseAddress address = new HTEnterpriseAddress();
        address.setContactPerson(contactPerson);
        address.setPhoneNumber(phoneNumber);
        address.setEnterpriseName(enterpriseName);

        try {
            enterpriseAddressService.save(address);
        } catch (Exception e) {
            throw new JeecgBootException("保存企业联系方式失败！");
        }

        return address;
    }

    @Override
    public Page<HTPlatformUser> queryUserListByCertificateAuditStatus(Page<HTPlatformUser> page, Integer certificateAuditStatus) {
        return page.setRecords(accountMapper.queryUserListByCertificateAuditStatus(page, certificateAuditStatus));
    }

    @Override
    @Transactional
    public boolean upgradeUser(HTAccountUpgradeBO bo) {
        boolean succeed = false;
        HTPlatformUser platformUser = null;
        if (oConvertUtils.isNotEmpty(bo.getPhoneNumber())) {
            platformUser = accountMapper.queryFrontendUserByPhoneNumber(bo.getPhoneNumber());
        }

        if (oConvertUtils.isNotEmpty(bo.getUsername()) && oConvertUtils.isEmpty(platformUser)) {
            platformUser = accountMapper.queryFrontendUserByUsername(bo.getUsername());
        }

        if (oConvertUtils.isNotEmpty(platformUser)) {
            bo.setPassword(platformUser.getPassword());
            bo.setSalt(platformUser.getSalt());
        }


        try {
            switch (bo.getUpgradeAccountType()) {
                case FORUMS_EXPERT:
                    HTForumsExpert expert = SmartBeanUtil.copy(bo, HTForumsExpert.class);
                    expert.setAccountType(HTAccountTypeEnum.FORUMS_EXPERT.getValue());
                    succeed = forumsExpertService.save(expert);
                    if (succeed) {
                        succeed = deleteCurrentAccount(bo);
                    }
                    break;

                case MERCHANT: {
                    HTAccountAddBO accountAddBO = SmartBeanUtil.copy(bo, HTAccountAddBO.class);
                    succeed = handleSignUpForMerchant(accountAddBO);
                    if (succeed) {
                        succeed = deleteCurrentAccount(bo);
                    }
                }
                break;

                case EVALUATION_AGENCY: {
                    HTEvaluationAgency evaluationAgency = SmartBeanUtil.copy(bo, HTEvaluationAgency.class);
                    evaluationAgency.setAccountType(HTAccountTypeEnum.EVALUATION_AGENCY.getValue());
                    HTAccountAddBO accountAddBO = SmartBeanUtil.copy(bo, HTAccountAddBO.class);
                    validateEnterpriseUserParameters(accountAddBO);
                    succeed = evaluationAgencyService.save(evaluationAgency);
                    try {
                        HTEnterpriseAddress address = saveEnterpriseAddress(bo.getContactPerson(),
                                bo.getPhoneNumber(), evaluationAgency.getEnterpriseName());
                        evaluationAgency.setEnterpriseAddressId(address.getId());
                        succeed = evaluationAgencyService.updateById(evaluationAgency);
                    } catch (Exception e) {
                        throw new JeecgBootException("更新失败！");
                    }

                    if (succeed) {
                        succeed = deleteCurrentAccount(bo);
                    }
                }
                break;

                case ALLIANCE: {
                    HTAlliance alliance = SmartBeanUtil.copy(bo, HTAlliance.class);
                    alliance.setAccountType(HTAccountTypeEnum.ALLIANCE.getValue());

                    HTAccountAddBO accountAddBO = SmartBeanUtil.copy(bo, HTAccountAddBO.class);
                    validateEnterpriseUserParameters(accountAddBO);
                    succeed = allianceService.save(alliance);

                    try {
                        HTEnterpriseAddress address = saveEnterpriseAddress(bo.getContactPerson(),
                                bo.getPhoneNumber(), alliance.getEnterpriseName());
                        alliance.setEnterpriseAddressId(address.getId());
                        succeed = allianceService.updateById(alliance);
                    } catch (Exception e) {
                        throw new JeecgBootException("更新失败！");
                    }
                    if (succeed) {
                        succeed = deleteCurrentAccount(bo);
                    }
                }
                break;

                case ALLIANCE_MEMBER: {
                    HTAllianceMember allianceMember = SmartBeanUtil.copy(bo, HTAllianceMember.class);
                    allianceMember.setAccountType(HTAccountTypeEnum.ALLIANCE_MEMBER.getValue());
                    HTAccountAddBO accountAddBO = SmartBeanUtil.copy(bo, HTAccountAddBO.class);
                    validateEnterpriseUserParameters(accountAddBO);
                    succeed = allianceMemberService.save(allianceMember);

                    //try {
                    //    HTEnterpriseAddress address = saveEnterpriseAddress(bo.getContactPerson(),
                    //            bo.getPhoneNumber(), allianceMember.getEnterpriseName());
                    //    allianceMember.setEnterpriseAddressId(address.getId());
                    //    succeed = allianceMemberService.updateById(allianceMember);
                    //} catch (Exception e) {
                    //    throw new JeecgBootException("更新失败！");
                    //}
                    if (succeed) {
                        succeed = deleteCurrentAccount(bo);
                    }
                }
                break;

                default:
                    break;
            }
        } catch (Exception e) {
            System.out.printf("\n\n\n upgrade user %s \n\n\n", JSONObject.toJSONString(e));
            throw new JeecgBootException("账户升级失败");
        }
        return succeed;
    }

    private boolean deleteCurrentAccount(HTAccountUpgradeBO bo) {
        boolean succeed = false;
        String id = bo.getId();
        try {
            switch (bo.getCurrentAccountType()) {
                case MEMBER:
                    succeed = memberService.removeById(id);
                    break;
                case FORUMS_EXPERT:
                    succeed = forumsExpertService.removeById(id);
                case MERCHANT:
                    succeed = merchantService.removeById(id);
                    break;

                case EVALUATION_AGENCY:
                    succeed = evaluationAgencyService.removeById(id);
                    break;

                case ALLIANCE_MEMBER:
                    succeed = allianceMemberService.removeById(id);
                    break;

                default:
                    break;
            }
        } catch (Exception e) {
            throw new JeecgBootException("移除旧账户失败");
        }

        return succeed;
    }

    @Override
    @Transactional
    public boolean bindTencentAccountBy(HTPlatformUser user) {
        boolean succeed = false;
        if (oConvertUtils.isNotEmpty(user)) {
            HTUserUpdateBO bo = SmartBeanUtil.copy(user, HTUserUpdateBO.class);
            bo.setTencentAccountId(user.getTencentAccountId());
            succeed = updateUserInfo(bo);
        }
        return succeed;
    }

    @Override
    public HTUserStatisticsVO queryStatistics(String dayTime) {
        return accountMapper.queryStatistics(dayTime);
    }
}
